(function (){
    var host = utils.rootPath;
    XMLHttpRequest.prototype.json = function (...args){
        const that = this;
        return new Promise(function (success,error){
            try{
                var data = JSON.parse(that.responseText);
                success(data);
            }catch (e){
                success(null);
            }
        });
    }
    window.httpUtil = {
        url:function (){
            return host+"/api.php?type=3";
        },
        xhrReq:function (method,url,data,progress,headerMap,xhr,responseType){
            if(!xhr){
                xhr = new XMLHttpRequest();
            }
            return new Promise(function (success,error){
                xhr.open(method, url);
                if(responseType){
                    xhr.responseType = responseType;
                }
                if(headerMap){
                    for(let key in headerMap){
                        let val = headerMap[key];
                        xhr.setRequestHeader(key,val);
                    }
                }
                xhr.addEventListener('loadend', function() {
                    if(xhr.readyState===4) {
                        success(xhr);
                    }
                });
                xhr.addEventListener('error', function() {
                    error();
                });
                xhr.addEventListener('progress', function(evt) {
                    if(progress){
                        progress(evt.loaded,evt.total,2);
                    }
                });
                xhr.upload.addEventListener('progress', function(evt) {
                    if(progress){
                        progress(evt.loaded,evt.total,1);
                    }
                });
                try{
                    xhr.send(data);
                }catch (e){
                    error();
                }
            });
        },
        proxy:function (url,method,headerMap,data,cdx,resHeaderMap,progress,responseType){
            var proxyUrl = new URL(this.url());
            proxyUrl.searchParams.set("url",btoa(url));
            if(!method){
                method = "GET";
            }
            var newMap = {};
            if(headerMap){
                var header = "";
                for (var key in headerMap){
                    newMap[key+"-back"] = headerMap[key];
                    header += ";"+key+"-back"+":"+key;
                }
                if(header.length>0){
                    header = header.substring(1);
                    proxyUrl.searchParams.set("header",btoa(header));
                }
            }
            if(resHeaderMap){
                var header = "";
                for (var key in resHeaderMap){
                    header += ";"+key+":"+resHeaderMap[key];
                }
                if(header.length>0){
                    header = header.substring(1);
                    proxyUrl.searchParams.set("resHeader",btoa(header));
                }
            }
            if(data){
                if(data instanceof Blob){
                    //单文件上传
                    const fd = new FormData();
                    fd.append('file', data);
                    data = fd;
                }else if(data instanceof FormData){
                    //带文件的表单上传
                }else{
                    data = JSON.stringify(data);
                    newMap["content-type"] = 'application/json;charset=utf-8';
                }
            }
            if(cdx){
                proxyUrl.searchParams.set("cdx",cdx);
            }
            var param = {
                method:method,
                headers:newMap
            }
            if(data){
                param.body = data;
            }
            return this.xhrReq(method,proxyUrl.href,param.body,progress,param.headers,null,responseType);
        }
    }
    window.autocad = {
        webosMethod:function (method,param){
            const that = this;
            return fetch(that.webosUrl+"/"+method,{
                method: 'POST',
                body: JSON.stringify(param),
                headers: {
                    "content-type":"application/json;charset=utf-8"
                }
            }).then(function (res){
                return res.json()
            });
        },
        uploadPre:function (p1,p2,p3){
            return this.webosMethod("uploadPre",{p1,p2,p3});
        },
        uploadAfter:function (p1,p2,p3){
            return this.webosMethod("uploadAfter",{p1,p2,p3});
        },
        fileInfo:function (p1){
            return this.webosMethod("fileInfo",{p1});
        },
        getExtByName:function (name){
            if(!name){
                name = "";
            }
            let sz = name.split(".");
            if(sz.length>1){
                return sz[sz.length-1].toLowerCase();
            }else{
                return "";
            }
        },
        getCadFileId:async function(options,status,fn,jdFn,comFn){
            const that = this;
            //status 0下载 1上传 2转码 3预览
            if(status == 0){
                if(jdFn){
                    jdFn("");
                }
                if(options.file_id){
                    //判断缓存
                    try{
                        const info = await that.fileInfo(that.autoCadPath+"/"+options.file_id);
                        if(info && info.data && info.data.path){
                            that.fileId = options.file_id;
                            fn(2,"");
                            return that.getCadFileId(options,2,fn,jdFn,comFn);
                        }
                    }catch (e){

                    }
                }
                //下载
                var cache_key = "file_cache_cad_"+(options.path?options.path:options.url);
                var blobPromise = new Promise(function (success,error){
                    utils.getBigData(cache_key,async function (data,flag){
                        if(data && flag){
                            success(data);
                        }else{
                            var xhr = await httpUtil.xhrReq("GET",options.url,undefined,function (loaded,total,type){
                                    if(type != 2){
                                        return;
                                    }
                                    const jd = (loaded*100/total).toFixed(2)+"%";
                                    if(jdFn){
                                        jdFn(jd);
                                    }
                                },
                                null,null,"blob");
                            success(xhr.response);
                        }
                    });
                });
                var blob = await blobPromise;
                if(!blob){
                    fn(0,"文件下载失败");
                    return "";
                }
                that.fileBlob = blob;
                utils.setBigData(cache_key,blob);
                fn(1,"");
                return that.getCadFileId(options,1,fn,jdFn,comFn);
            }
            if(status == 1){
                if(jdFn){
                    jdFn("");
                }
                const uploadData = await new Promise(function (success,error){
                    const fileParam = {
                        status:1,
                        statusChange:function (res){
                            success(res);
                        },
                        size:that.fileBlob.size,
                        file:that.fileBlob,
                        path:that.autoCadPath,
                        filePath:options.name
                    }
                    autocadUpload.upload(fileParam,function (loaded,total,type){
                        if(type != 1){
                            return;
                        }
                        const jd = (loaded*100/total).toFixed(2)+"%";
                        if(jdFn){
                            jdFn(jd);
                        }
                    });
                });
                if(!uploadData || !uploadData.uploadPreRes || !uploadData.uploadPreRes.fileId){
                    fn(1,uploadData&&uploadData.msg?uploadData.msg:"文件上传失败");
                    return "";
                }
                if(jdFn){
                    jdFn("100%");
                }
                that.fileId = uploadData.uploadPreRes.fileId;
                fn(2,"");
                return that.getCadFileId(options,2,fn,jdFn,comFn);
            }
            if(status == 2){
                jdFn("0%");
                let count = 0;
                while(true){
                    const flag = await new Promise(async function (success,error){
                        const flag = await comFn(that.fileId);
                        if(flag){
                            success(true);
                        }else{
                            setTimeout(function (){
                                success(false);
                            },3000);
                        }
                    });
                    if(flag){
                        break;
                    }
                    count++;
                    let val = count*5;
                    if(val > 99){
                        val = 99;
                    }
                    jdFn(val+"%");
                }
                return that.fileId;
            }
        }
    }
})()